import re

from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from goods.models import SKU
from mall import settings
from users.models import User, Address
from celery_tasks.email.tasks import send_verify_mail

"""用户历史记录"""


class UserHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label='商品编号', min_value=1, required=True)

    def validate_sku_id(self, value):
        # 校验商品是否存在
        try:
            SKU.objects.get(pk=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')
        return value

    # 获取用户信息和商品id，保存数据到redis
    def create(self, validated_data):
        # 获取商品id
        sku_id = validated_data.get('sku_id')
        # 获取用户id ,当做键进行保存
        user_id = self.context['request'].user.id
        # 保存到redis
        # 1.连接数据库
        redis_conn = get_redis_connection('history')
        # 2.移除已经存在的数据
        redis_conn.lrem('history_%s' % user_id, 0, sku_id)
        # 3.添加数据
        redis_conn.lpush('history_%s' % user_id, sku_id)
        # 4.设置最多保存５条记录
        redis_conn.ltrim('history_%s' % user_id, 0, 4)

        return validated_data


"""地址标题"""


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """

    class Meta:
        model = Address
        fields = ['title', ]


"""用户地址信息"""


class AddressSerializer(serializers.ModelSerializer):
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def create(self, validated_data):
        # Address模型类中有user属性,将user对象添加到模型类的创建参数中
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


"""校验,保存邮箱信息"""


class EmailSerializer(serializers.ModelSerializer):
    """
    邮箱序列化器
    """

    class Meta:
        model = User
        fields = ('id', 'email')
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        email = validated_data.get('email')
        instance.email = email
        instance.save()
        """""发送邮件"""

        from django.core.mail import send_mail

        # subject, message, from_email, recipient_list,html_message=None
        # subject: 主题
        subject = '美多商城激活邮件'
        # message,  内容,普通内容
        message = ''
        # from_email,  谁发送的
        from_email = settings.EMAIL_FROM
        # recipient_list: 谁接收 []
        recipient_list = [email]
        # html_message  , 丰富的邮件内容可以传递 html
        # html_message = '<h1>lalala</h1>'

        # 生成一个 对id和email进行处理的一个url
        verify_url = instance.generice_active_url()

        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)
        send_verify_mail.delay(subject, message, from_email, recipient_list, html_message)
        # send_mail(subject, message, from_email, recipient_list, html_message=html_message)

        return instance


"""用户详情"""


class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详细信息序列化器
    """

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


"""注册用户"""


class RegisterCreateSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(label='校验密码', allow_null=False, allow_blank=False, write_only=True)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, allow_null=False, allow_blank=False,
                                     write_only=True)
    allow = serializers.CharField(label='是否同意协议', allow_null=False, allow_blank=False, write_only=True)
    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'mobile', 'password2', 'sms_code', 'allow', 'token')
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        if not re.match(r'1[345789]\d{9}', value):
            raise serializers.ValidationError('手机号格式不正确')
        return value

    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('请同意协议')
        return value

    def validate(self, attrs):
        # 校验密码
        password = attrs.get('password')
        password2 = attrs.get('password2')
        if password != password2:
            raise serializers.ValidationError('密码不一致')
        # 校验验证码
        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')
        redis_conn = get_redis_connection('code')
        redis_code = redis_conn.get('sms_%s' % mobile)
        if sms_code != redis_code.decode():
            raise serializers.ValidationError('验证码不正确')
        return attrs

    def create(self, validated_data):
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = super().create(validated_data)

        user.set_password(validated_data['password'])
        user.save()

        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user
